package com.demo.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.ClientEndpoint;
import javax.websocket.*;

/**
 * @author ZM
 * WebSocket客户端【将此项目作为客户端，向其他按项目发送数据】
 */
@ClientEndpoint
@Component
@Slf4j
public class MyClientSocket {

    private Session session;

    //建立连接
    @OnOpen
    public void open(Session session){
        log.info("Client WebSocket 已打开...");
        this.session = session;
    }

    //接收到服务端消息后调用
    @OnMessage
    public void onMessage(String message){
        log.info("服务端发来消息: " + message);
    }

    //连接关闭
    @OnClose
    public void onClose(){
        log.info("Websocket Server 端关闭了......");
    }

    /**
     * 发送客户端消息到服务端
     * @param message 消息内容
     */
    public  void send(String message){
        this.session.getAsyncRemote().sendText(message);
    }

}
